# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Create Time  : 2024/4/2 17:43
# @Author       : kony.xie
# @File Name    : getCPU.py
# @Python Ver.  : Python 3.8.10
# @Description  : It is used to obtain CPU data from Prometheus and determine whether the CPU exceeds the threshold.
#                 Currently, it is not in use.
# -------------------------------------------------------------------------------
import requests, time

def pronodeip(result):
    try:
        list = [item['metric']['instance'] for item in result['data']['result']]
    except:
        print(result)
    return list

def getvalue(result):
    valuelist = [item for item in result['data']['result'][0]['value']]
    value = round(float(valuelist[1]), 1)
    return value

def reqPrometheus(url):
    try:
        response = requests.get(url, timeout=5)
        resdict = eval(response.text)
    except:
        resdict = {}
    return resdict

# 获取node节点ip
def getnodeip(host, datetime):
    result = {'Linux': [], 'Win': []}
    # 获取linxu节点
    url = 'http://' + host + '/api/v1/query?query=node_exporter_build_info&time=%s' % (datetime)
    data = reqPrometheus(url)
    if len(data) > 0:
        result['Linux'] = pronodeip(data)
    # 获取windows节点
    urlwindows = 'http://' + host + '/api/v1/query?query=windows_exporter_build_info&time=%s' % (datetime)
    data = reqPrometheus(urlwindows)
    if len(data) > 0:
        result['Win'] = pronodeip(data)
    return result

class GetCPU():       
    # 获取cpu使用率
    def getcpuuse(self, host, datetime):
        nodeipdict = getnodeip(host, datetime)
        result = []
        # Linux系统
        if len(nodeipdict['Linux']) > 0:
            for nodeip in nodeipdict['Linux']:
                expr = '100-(avg(irate(node_cpu_seconds_total{instance="%s",mode=\"idle\"}[1m])))*100' % nodeip
                url = 'http://' + host + "/api/v1/query?query=%s&time=%s" % (expr, datetime)
                data = reqPrometheus(url)
                result.append(getvalue(data))
        # Win系统
        if len( nodeipdict['Win']) > 0:
            for nodeip in nodeipdict['Win']:
                expr = '100-(avg(irate(windows_cpu_time_total{instance="%s",mode=\"idle\"}[1m])) * 100)' % nodeip
                url = 'http://' + host + "/api/v1/query?query=%s&time=%s" % (expr, datetime)
                data = reqPrometheus(url)
                result.append(getvalue(data))
        return result

    def isStart(self, host, datetime, threshold):
        flag = False
        cpuuse = self.getcpuuse(host, datetime)
        for cpu in cpuuse:
            if cpu > threshold:
                print("cpu exceeded threshold")
                time.sleep(30)
                flag = True
                break
        return flag
